<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>FFmpeg调试测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
        }
        .debug-section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .log-output {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 3px;
            font-family: monospace;
            font-size: 12px;
            max-height: 300px;
            overflow-y: auto;
            white-space: pre-wrap;
        }
        .error {
            background: #f8d7da;
            border-color: #f5c6cb;
            color: #721c24;
        }
        .success {
            background: #d4edda;
            border-color: #c3e6cb;
            color: #155724;
        }
        .warning {
            background: #fff3cd;
            border-color: #ffeaa7;
            color: #856404;
        }
        button {
            padding: 10px 20px;
            margin: 5px;
            border: none;
            border-radius: 3px;
            background: #007bff;
            color: white;
            cursor: pointer;
        }
        button:hover {
            background: #0056b3;
        }
        button:disabled {
            background: #6c757d;
            cursor: not-allowed;
        }
        .file-info {
            background: #e9ecef;
            padding: 10px;
            border-radius: 3px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <h1>🔍 FFmpeg调试测试</h1>
    
    <div class="debug-section">
        <h3>1. 选择测试文件</h3>
        <input type="file" id="testFile" accept="video/*">
        <div id="fileInfo" class="file-info" style="display: none;"></div>
    </div>

    <div class="debug-section">
        <h3>2. FFmpeg状态检查</h3>
        <button onclick="checkFFmpegStatus()" id="checkBtn">检查FFmpeg状态</button>
        <div id="ffmpegStatus" class="log-output"></div>
    </div>

    <div class="debug-section">
        <h3>3. 文件格式分析</h3>
        <button onclick="analyzeFile()" id="analyzeBtn" disabled>分析文件格式</button>
        <div id="analysisResult" class="log-output"></div>
    </div>

    <div class="debug-section">
        <h3>4. FFmpeg处理测试</h3>
        <button onclick="testFFmpegProcessing()" id="processBtn" disabled>测试FFmpeg处理</button>
        <div id="processResult" class="log-output"></div>
    </div>

    <div class="debug-section">
        <h3>5. 调试日志</h3>
        <div id="debugLog" class="log-output"></div>
    </div>

    <!-- FFmpeg.wasm 库 -->
    <script src="https://unpkg.com/@ffmpeg/ffmpeg@0.10.1/dist/ffmpeg.min.js"></script>

    <script>
        let ffmpeg = null;
        let selectedFile = null;

        function log(message, type = 'info') {
            const debugLog = document.getElementById('debugLog');
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = `[${timestamp}] ${message}\n`;
            debugLog.textContent += logEntry;
            debugLog.scrollTop = debugLog.scrollHeight;
            console.log(`[${type}] ${message}`);
        }

        function updateSection(sectionId, content, type = 'info') {
            const section = document.getElementById(sectionId);
            section.textContent = content;
            section.className = `log-output ${type}`;
        }

        // 文件选择处理
        document.getElementById('testFile').addEventListener('change', (e) => {
            selectedFile = e.target.files[0];
            if (selectedFile) {
                const fileInfo = document.getElementById('fileInfo');
                fileInfo.innerHTML = `
                    <strong>文件名:</strong> ${selectedFile.name}<br>
                    <strong>大小:</strong> ${formatFileSize(selectedFile.size)}<br>
                    <strong>类型:</strong> ${selectedFile.type}<br>
                    <strong>最后修改:</strong> ${new Date(selectedFile.lastModified).toLocaleString()}
                `;
                fileInfo.style.display = 'block';
                
                document.getElementById('analyzeBtn').disabled = false;
                document.getElementById('processBtn').disabled = false;
                
                log(`文件已选择: ${selectedFile.name} (${formatFileSize(selectedFile.size)})`);
            }
        });

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        async function checkFFmpegStatus() {
            const btn = document.getElementById('checkBtn');
            btn.disabled = true;
            btn.textContent = '检查中...';
            
            try {
                updateSection('ffmpegStatus', '正在检查FFmpeg状态...', 'info');
                log('开始检查FFmpeg状态');
                
                // 检查FFmpeg库是否加载
                if (typeof FFmpeg === 'undefined') {
                    throw new Error('FFmpeg库未加载');
                }
                
                // 创建FFmpeg实例
                if (!ffmpeg) {
                    log('创建FFmpeg实例...');
                    ffmpeg = FFmpeg.createFFmpeg({
                        log: true,
                        corePath: 'https://unpkg.com/@ffmpeg/core@0.10.0/dist/ffmpeg-core.js'
                    });
                }
                
                // 加载FFmpeg
                if (!ffmpeg.isLoaded()) {
                    log('加载FFmpeg核心...');
                    await ffmpeg.load();
                }
                
                // 测试基本命令
                log('测试FFmpeg基本功能...');
                await ffmpeg.run('-version');
                
                updateSection('ffmpegStatus', '✅ FFmpeg状态正常\n- 库已加载\n- 核心已初始化\n- 基本命令测试通过', 'success');
                log('FFmpeg状态检查完成');
                
            } catch (error) {
                const errorMsg = `❌ FFmpeg状态异常: ${error.message}`;
                updateSection('ffmpegStatus', errorMsg, 'error');
                log(`FFmpeg状态检查失败: ${error.message}`);
            } finally {
                btn.disabled = false;
                btn.textContent = '检查FFmpeg状态';
            }
        }

        async function analyzeFile() {
            if (!selectedFile) {
                alert('请先选择文件');
                return;
            }
            
            const btn = document.getElementById('analyzeBtn');
            btn.disabled = true;
            btn.textContent = '分析中...';
            
            try {
                updateSection('analysisResult', '正在分析文件格式...', 'info');
                log('开始分析文件格式');
                
                // 读取文件头
                const headerSize = Math.min(1024, selectedFile.size);
                const header = await selectedFile.slice(0, headerSize).arrayBuffer();
                const headerView = new Uint8Array(header);
                
                let analysis = `文件分析结果:\n`;
                analysis += `文件大小: ${formatFileSize(selectedFile.size)}\n`;
                analysis += `MIME类型: ${selectedFile.type}\n\n`;
                
                // 检查文件格式
                let formatDetected = false;
                
                // 检查MP4/MOV
                for (let i = 0; i < Math.min(headerView.length - 8, 100); i++) {
                    if (headerView[i] === 0x66 && headerView[i+1] === 0x74 && 
                        headerView[i+2] === 0x79 && headerView[i+3] === 0x70) {
                        analysis += `✅ 检测到MP4/MOV格式 (ftyp box at offset ${i})\n`;
                        formatDetected = true;
                        break;
                    }
                }
                
                // 检查AVI
                if (!formatDetected) {
                    for (let i = 0; i < Math.min(headerView.length - 8, 100); i++) {
                        if (headerView[i] === 0x52 && headerView[i+1] === 0x49 && 
                            headerView[i+2] === 0x46 && headerView[i+3] === 0x46) {
                            analysis += `✅ 检测到AVI格式 (RIFF header at offset ${i})\n`;
                            formatDetected = true;
                            break;
                        }
                    }
                }
                
                if (!formatDetected) {
                    analysis += `⚠️ 未识别的格式\n`;
                }
                
                // 显示文件头
                analysis += `\n文件头 (前32字节):\n`;
                const headerHex = Array.from(headerView.slice(0, 32))
                    .map(b => b.toString(16).padStart(2, '0'))
                    .join(' ');
                analysis += headerHex;
                
                // 检查FastStart状态
                let hasFastStart = false;
                for (let i = 0; i < Math.min(headerView.length - 8, 1000); i++) {
                    if (headerView[i] === 0x6D && headerView[i+1] === 0x6F && 
                        headerView[i+2] === 0x6F && headerView[i+3] === 0x76) {
                        if (i < 100) {
                            analysis += `\n✅ 可能已有FastStart优化 (moov box at offset ${i})`;
                            hasFastStart = true;
                        } else {
                            analysis += `\n❌ 需要FastStart优化 (moov box at offset ${i})`;
                        }
                        break;
                    }
                }
                
                if (!hasFastStart) {
                    analysis += `\n❓ 未找到moov box，可能不是标准MP4格式`;
                }
                
                updateSection('analysisResult', analysis, formatDetected ? 'success' : 'warning');
                log('文件格式分析完成');
                
            } catch (error) {
                const errorMsg = `❌ 文件分析失败: ${error.message}`;
                updateSection('analysisResult', errorMsg, 'error');
                log(`文件分析失败: ${error.message}`);
            } finally {
                btn.disabled = false;
                btn.textContent = '分析文件格式';
            }
        }

        async function testFFmpegProcessing() {
            if (!selectedFile) {
                alert('请先选择文件');
                return;
            }
            
            if (!ffmpeg || !ffmpeg.isLoaded()) {
                alert('请先检查FFmpeg状态');
                return;
            }
            
            const btn = document.getElementById('processBtn');
            btn.disabled = true;
            btn.textContent = '处理中...';
            
            try {
                updateSection('processResult', '开始FFmpeg处理测试...', 'info');
                log('开始FFmpeg处理测试');
                
                const inputFileName = 'test_input.mp4';
                const outputFileName = 'test_output.mp4';
                
                // 写入文件到FFmpeg
                log('写入文件到FFmpeg虚拟文件系统...');
                const fileData = new Uint8Array(await selectedFile.arrayBuffer());
                ffmpeg.FS('writeFile', inputFileName, fileData);
                log(`文件写入完成: ${formatFileSize(fileData.length)}`);
                
                // 设置详细日志
                let ffmpegLogs = [];
                ffmpeg.setLogger(({ type, message }) => {
                    ffmpegLogs.push(`[${type}] ${message}`);
                    log(`FFmpeg [${type}]: ${message}`);
                });
                
                // 执行FFmpeg命令
                log('执行FFmpeg命令...');
                await ffmpeg.run('-i', inputFileName, '-c', 'copy', '-movflags', 'faststart', outputFileName);
                
                // 检查输出
                let result = 'FFmpeg处理完成!\n\n';
                
                try {
                    const outputData = ffmpeg.FS('readFile', outputFileName);
                    result += `✅ 输出文件大小: ${formatFileSize(outputData.length)}\n`;
                    
                    if (outputData.length > 0) {
                        result += `✅ 处理成功\n`;
                        
                        // 检查输出文件头
                        const outputHeader = new Uint8Array(outputData.buffer.slice(0, 32));
                        const outputHex = Array.from(outputHeader)
                            .map(b => b.toString(16).padStart(2, '0'))
                            .join(' ');
                        result += `输出文件头: ${outputHex}\n`;
                        
                    } else {
                        result += `❌ 输出文件为空\n`;
                    }
                } catch (readError) {
                    result += `❌ 无法读取输出文件: ${readError.message}\n`;
                }
                
                // 显示FFmpeg日志
                result += `\nFFmpeg日志 (最后10条):\n`;
                result += ffmpegLogs.slice(-10).join('\n');
                
                // 清理文件
                try {
                    ffmpeg.FS('unlink', inputFileName);
                    ffmpeg.FS('unlink', outputFileName);
                    log('临时文件已清理');
                } catch (e) {
                    log('清理临时文件失败: ' + e.message);
                }
                
                updateSection('processResult', result, 'success');
                log('FFmpeg处理测试完成');
                
            } catch (error) {
                const errorMsg = `❌ FFmpeg处理失败: ${error.message}`;
                updateSection('processResult', errorMsg, 'error');
                log(`FFmpeg处理测试失败: ${error.message}`);
            } finally {
                btn.disabled = false;
                btn.textContent = '测试FFmpeg处理';
            }
        }

        // 页面加载时自动检查FFmpeg
        window.addEventListener('load', () => {
            log('页面加载完成，开始初始化');
            setTimeout(() => {
                checkFFmpegStatus();
            }, 1000);
        });
    </script>
</body>
</html>